package com.yuyou.fn.updater.handler;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yuyou.fn.common.database.event.EventHandler;
import com.yuyou.fn.common.database.event.IEventHandler;
import com.yuyou.fn.common.util.Utils;
import com.yuyou.fn.portal.repository.OuterCampusRepository;
import com.yuyou.fn.portal.vo.OuterCampus;
import org.springframework.data.geo.Point;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@EventHandler(tables = "yyfn.campus")
@Component
public class OuterCampusUpdater implements IEventHandler{

    @Resource
    private OuterCampusRepository outerCampusRepository;

    @Override
    public void insert(String tableName, JSONArray rowList) {
        List<OuterCampus> outerCampusList=toOuterCampus(rowList,false);
        outerCampusRepository.save(outerCampusList);
    }

    @Override
    public void update(String tableName, JSONArray rowList, Set<String> updateColumns) {

        List<OuterCampus> outerCampusList=toOuterCampus(rowList,false);
        outerCampusRepository.save(outerCampusList);

    }

    @Override
    public void delete(String tableName, JSONArray rowList) {

        List<OuterCampus> outerCampusList=toOuterCampus(rowList,true);
        outerCampusRepository.delete(outerCampusList);

    }

    private List<OuterCampus> toOuterCampus(JSONArray rowList , boolean isDelete) {
        List<OuterCampus> outerCampusList = new ArrayList<>(rowList.size());
        for (int i = 0; i < rowList.size(); i++) {
            JSONObject row = processFiled(rowList.getJSONObject(i) );
            OuterCampus outerCampus = row.toJavaObject(OuterCampus.class);
            if(!isDelete){
                fillExtra(outerCampus);
            }
            outerCampusList.add(outerCampus);
        }
        return outerCampusList;
    }
    private JSONObject processFiled(JSONObject row) {
        JSONObject nRow = new JSONObject();
        for(String key : row.keySet()){
            nRow.put(Utils.camelCase(key),row.get(key));
        }
        return nRow ;
    }

    private void fillExtra(OuterCampus outerCampus) {
        String[] locations=outerCampus.getGeoLocation()==null?"0 0".split(" "):outerCampus.getGeoLocation().split(" ");
        if(locations.length>=2){
            Point point=new Point(Double.parseDouble(locations[0]),Double.parseDouble(locations[1]));
            outerCampus.setCampusLocation(point);
        }
    }
}
